package jfconfig;

/**
 * Created : Mar 9, 2012
 *
 * @author pquiring
 */

import java.io.*;
import java.util.*;
import javax.swing.*;

import javaforce.*;
import javaforce.linux.*;

public class ApachePanel extends javax.swing.JPanel {

  /**
   * Creates new form ApachePanel
   */
  public ApachePanel() {
    initComponents();
    loadConfig();
    ConfigApp.This.setTitle("Config : Apache");
    Linux.detectDistro();
    if (Linux.distro != Linux.DistroTypes.Ubuntu) {
      runWizard.setEnabled(false);
      runWizard.setToolTipText("Requires Ubuntu");
    }
  }

  /**
   * This method is called from within the constructor to initialize the form.
   * WARNING: Do NOT modify this code. The content of this method is always
   * regenerated by the Form Editor.
   */
  @SuppressWarnings("unchecked")
  // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
  private void initComponents() {

    jToolBar1 = new javax.swing.JToolBar();
    back = new javax.swing.JButton();
    addvhost = new javax.swing.JButton();
    delvhost = new javax.swing.JButton();
    save = new javax.swing.JButton();
    apply = new javax.swing.JButton();
    restart = new javax.swing.JButton();
    jScrollPane1 = new javax.swing.JScrollPane();
    hosts = new javax.swing.JList();
    jTabbedPane1 = new javax.swing.JTabbedPane();
    jPanel1 = new javax.swing.JPanel();
    jLabel4 = new javax.swing.JLabel();
    docPath = new javax.swing.JTextField();
    domains = new javax.swing.JTextField();
    jLabel3 = new javax.swing.JLabel();
    port = new javax.swing.JTextField();
    jLabel1 = new javax.swing.JLabel();
    jLabel5 = new javax.swing.JLabel();
    name = new javax.swing.JTextField();
    ssl = new javax.swing.JCheckBox();
    enabled = new javax.swing.JCheckBox();
    cgi = new javax.swing.JCheckBox();
    manageFiles = new javax.swing.JButton();
    jLabel7 = new javax.swing.JLabel();
    wizards = new javax.swing.JComboBox();
    runWizard = new javax.swing.JButton();
    jLabel9 = new javax.swing.JLabel();
    wizardsDest = new javax.swing.JComboBox();
    jButton1 = new javax.swing.JButton();
    enableSSL = new javax.swing.JButton();

    jToolBar1.setFloatable(false);
    jToolBar1.setRollover(true);

    back.setText("<Back");
    back.setFocusable(false);
    back.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    back.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    back.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        backActionPerformed(evt);
      }
    });
    jToolBar1.add(back);

    addvhost.setText("Add Virtual Host");
    addvhost.setFocusable(false);
    addvhost.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    addvhost.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    addvhost.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        addvhostActionPerformed(evt);
      }
    });
    jToolBar1.add(addvhost);

    delvhost.setText("Delete Virtual Host");
    delvhost.setFocusable(false);
    delvhost.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    delvhost.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    delvhost.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        delvhostActionPerformed(evt);
      }
    });
    jToolBar1.add(delvhost);

    save.setText("Save");
    save.setFocusable(false);
    save.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    save.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    save.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        saveActionPerformed(evt);
      }
    });
    jToolBar1.add(save);

    apply.setText("Apply");
    apply.setFocusable(false);
    apply.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    apply.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    apply.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        applyActionPerformed(evt);
      }
    });
    jToolBar1.add(apply);

    restart.setText("Restart Server");
    restart.setFocusable(false);
    restart.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    restart.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    restart.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        restartActionPerformed(evt);
      }
    });
    jToolBar1.add(restart);

    hosts.setModel(hostsModel);
    hosts.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
    hosts.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
      public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
        hostsValueChanged(evt);
      }
    });
    jScrollPane1.setViewportView(hosts);

    jLabel4.setText("Documents");

    docPath.setText("/var/www");

    domains.setText("*");

    jLabel3.setText("Domains");
    jLabel3.setToolTipText("Domains (comma list)");

    port.setText("80");

    jLabel1.setText("Port");

    jLabel5.setText("Name");

    name.setEditable(false);
    name.setText("Default");

    ssl.setText("SSL (Secure)");

    enabled.setText("Enabled");

    cgi.setText("Enable CGI Support (/usr/lib/cgi-bin)");

    manageFiles.setText("Manage Files...");
    manageFiles.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        manageFilesActionPerformed(evt);
      }
    });

    jLabel7.setText("Load:");

    wizards.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "WordPress", "Drupal", "myPHPAdmin" }));

    runWizard.setText("Execute");
    runWizard.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        runWizardActionPerformed(evt);
      }
    });

    jLabel9.setText("as");

    wizardsDest.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Entire Website", "Virtual Folder" }));

    jButton1.setText("Launch SSL Key Manager...");
    jButton1.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        jButton1ActionPerformed(evt);
      }
    });

    enableSSL.setText("Enable SSL Module");
    enableSSL.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        enableSSLActionPerformed(evt);
      }
    });

    javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
    jPanel1.setLayout(jPanel1Layout);
    jPanel1Layout.setHorizontalGroup(
      jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(jPanel1Layout.createSequentialGroup()
        .addContainerGap()
        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
          .addComponent(ssl, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
          .addGroup(jPanel1Layout.createSequentialGroup()
            .addComponent(jLabel1)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(port))
          .addGroup(jPanel1Layout.createSequentialGroup()
            .addComponent(jLabel3)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(domains))
          .addGroup(jPanel1Layout.createSequentialGroup()
            .addComponent(jLabel4)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(docPath))
          .addGroup(jPanel1Layout.createSequentialGroup()
            .addComponent(jLabel5)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(name))
          .addGroup(jPanel1Layout.createSequentialGroup()
            .addComponent(jLabel7)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(wizards, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(jLabel9)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(wizardsDest, 0, 95, Short.MAX_VALUE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(runWizard))
          .addGroup(jPanel1Layout.createSequentialGroup()
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
              .addComponent(enabled)
              .addComponent(jButton1)
              .addComponent(cgi)
              .addComponent(manageFiles)
              .addComponent(enableSSL))
            .addGap(0, 0, Short.MAX_VALUE)))
        .addContainerGap())
    );
    jPanel1Layout.setVerticalGroup(
      jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(jPanel1Layout.createSequentialGroup()
        .addContainerGap()
        .addComponent(enabled)
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
          .addComponent(jLabel5)
          .addComponent(name, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
          .addComponent(jLabel1)
          .addComponent(port, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
          .addComponent(jLabel3)
          .addComponent(domains, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
          .addComponent(jLabel4)
          .addComponent(docPath, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addComponent(ssl)
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addComponent(jButton1)
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
        .addComponent(cgi)
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addComponent(manageFiles)
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
          .addComponent(jLabel7)
          .addComponent(wizards, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
          .addComponent(runWizard)
          .addComponent(jLabel9)
          .addComponent(wizardsDest, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        .addGap(18, 18, 18)
        .addComponent(enableSSL)
        .addContainerGap(357, Short.MAX_VALUE))
    );

    jTabbedPane1.addTab("General", jPanel1);

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
    this.setLayout(layout);
    layout.setHorizontalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addComponent(jToolBar1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
      .addGroup(layout.createSequentialGroup()
        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 108, javax.swing.GroupLayout.PREFERRED_SIZE)
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE))
    );
    layout.setVerticalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(layout.createSequentialGroup()
        .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
          .addComponent(jScrollPane1)
          .addComponent(jTabbedPane1)))
    );
  }// </editor-fold>//GEN-END:initComponents

  private void backActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_backActionPerformed
    ConfigApp.This.setPanel(new ServersPanel());
  }//GEN-LAST:event_backActionPerformed

  private void hostsValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_hostsValueChanged
    int idx = hosts.getSelectedIndex();
    if (idx == -1) return;
    loadHost(idx);
  }//GEN-LAST:event_hostsValueChanged

  private void addvhostActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addvhostActionPerformed
    String name = JFAWT.getString("Enter Virtual Host Name", "");
    if (name == null) return;
    addHost(name);
  }//GEN-LAST:event_addvhostActionPerformed

  private void delvhostActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_delvhostActionPerformed
    int idx = hosts.getSelectedIndex();
    if (idx == -1) return;
    delHost(idx);
  }//GEN-LAST:event_delvhostActionPerformed

  private void applyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_applyActionPerformed
    apply();
  }//GEN-LAST:event_applyActionPerformed

  private void saveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveActionPerformed
    saveConfig();
  }//GEN-LAST:event_saveActionPerformed

  private void restartActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_restartActionPerformed
    restart();
  }//GEN-LAST:event_restartActionPerformed

  private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
    int idx = hosts.getSelectedIndex();
    if (idx == -1) {
      return;
    }
    Host host = config.host[idx];
    String folder = "/etc/jconfig.d/apache/" + host.name;
    OpenSSLApp dialog = new OpenSSLApp(new String[]{folder, "apache"});
    dialog.setVisible(true);
  }//GEN-LAST:event_jButton1ActionPerformed

  private void runWizardActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_runWizardActionPerformed
    int idx = hosts.getSelectedIndex();
    if (idx == -1) {
      return;
    }
    Host host = config.host[idx];
    switch (wizards.getSelectedIndex()) {
      case 0:  //install WordPress
        if (!JFAWT.showConfirm("Warning", "You are about to install WordPress CMS")) {
          return;
        }
        if (!Linux.installPackage("wordpress", "WordPress")) {
          JFAWT.showError("Error", "Failed to install WordPress");
          return;
        }
        if (wizardsDest.getSelectedIndex() == 0) {
          host.docPath = "/usr/share/wordpress";
        } else {
          //TODO : create virtual folder
        }
        break;
      case 1:  //install Drupal
        if (!JFAWT.showConfirm("Warning", "You are about to install Drupal CMS")) {
          return;
        }
        if (!Linux.installPackage("drupal6", "Drupal")) {
          JFAWT.showError("Error", "Failed to install WordPress");
          return;
        }
        if (wizardsDest.getSelectedIndex() == 0) {
          host.docPath = "/usr/share/drupal6";
        } else {
          //create virtual folder (link)
          String folder = JFAWT.getString("Enter virtual name", "");
          if ((folder == null) || (folder.length() == 0)) {
            break;
          }
          Linux.runScript(new String[]{
                    "ln -s /usr/share/drupal6 " + host.docPath + "/" + folder
                  });
        }
        break;
      case 2:  //install myPHPAdmin
        if (!JFAWT.showConfirm("Warning", "You are about to install myPHPAdmin")) {
          return;
        }
        if (!Linux.installPackage("myphpadmin", "myPHPAdmin")) {
          JFAWT.showError("Error", "Failed to install myPHPAdmin");
          return;
        }
        if (wizardsDest.getSelectedIndex() == 0) {
          host.docPath = "/usr/share/myphpadmin";
        } else {
          //create virtual folder (link)
          String folder = JFAWT.getString("Enter virtual name", "");
          if ((folder == null) || (folder.length() == 0)) {
            break;
          }
          Linux.runScript(new String[]{
                    "ln -s /usr/share/myphpadmin " + host.docPath + "/" + folder
                  });
        }
        break;
    }
  }//GEN-LAST:event_runWizardActionPerformed

  private void manageFilesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_manageFilesActionPerformed
    JFAWT.showError("Note", "Not implemented yet");  //pending jfile
  }//GEN-LAST:event_manageFilesActionPerformed

  private void enableSSLActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_enableSSLActionPerformed
    if (!Linux.runScript(new String[] {"a2enmod", "ssl"})) {
      JFAWT.showError("Error", "Failed to enable mod_ssl");
    } else {
      JFAWT.showMessage("Notice", "Enabled mod_ssl");
    }
  }//GEN-LAST:event_enableSSLActionPerformed

  // Variables declaration - do not modify//GEN-BEGIN:variables
  private javax.swing.JButton addvhost;
  private javax.swing.JButton apply;
  private javax.swing.JButton back;
  private javax.swing.JCheckBox cgi;
  private javax.swing.JButton delvhost;
  private javax.swing.JTextField docPath;
  private javax.swing.JTextField domains;
  private javax.swing.JButton enableSSL;
  private javax.swing.JCheckBox enabled;
  private javax.swing.JList hosts;
  private javax.swing.JButton jButton1;
  private javax.swing.JLabel jLabel1;
  private javax.swing.JLabel jLabel3;
  private javax.swing.JLabel jLabel4;
  private javax.swing.JLabel jLabel5;
  private javax.swing.JLabel jLabel7;
  private javax.swing.JLabel jLabel9;
  private javax.swing.JPanel jPanel1;
  private javax.swing.JScrollPane jScrollPane1;
  private javax.swing.JTabbedPane jTabbedPane1;
  private javax.swing.JToolBar jToolBar1;
  private javax.swing.JButton manageFiles;
  private javax.swing.JTextField name;
  private javax.swing.JTextField port;
  private javax.swing.JButton restart;
  private javax.swing.JButton runWizard;
  private javax.swing.JButton save;
  private javax.swing.JCheckBox ssl;
  private javax.swing.JComboBox wizards;
  private javax.swing.JComboBox wizardsDest;
  // End of variables declaration//GEN-END:variables

  private DefaultListModel hostsModel = new DefaultListModel();
  private String configFolder = "/etc/jconfig.d/";
  private String configFile = "apache.xml";
  public static class Host {
    public boolean enabled, cgi, ssl;
    public String name, domains, docPath;
    public int port;
  }
  public static class Config {
    public Host host[];
  }
  private Config config = new Config();
  private int currentIdx = -1;

  private void loadConfig() {
    try {
      XML xml = new XML();
      FileInputStream fis = new FileInputStream(configFolder + configFile);
      xml.read(fis);
      xml.writeClass(config);
    } catch (FileNotFoundException e1) {
      defaultConfig();
    } catch (Exception e2) {
      JFLog.log(e2);
      defaultConfig();
    }
    updateConfig();
  }

  private void defaultConfig() {
    //creates the init default config
    Host host1 = new Host();
    host1.name = "default";
    host1.port = 80;
    host1.domains = "*";
    host1.docPath = "/var/www";
    host1.enabled = true;
    Host host2 = new Host();
    host2.name = "default-ssl";
    host2.port = 443;
    host2.ssl = true;
    host2.domains = "_default_";
    host2.docPath = "/var/www";
    host2.enabled = false;
    config.host = new Host[2];
    config.host[0] = host1;
    config.host[1] = host2;
  }

  private void updateConfig() {
    //update hosts to config data
    hosts.clearSelection();
    hostsModel.clear();
    int cnt = config.host.length;
    for(int a=0;a<cnt;a++) {
      hostsModel.addElement(config.host[a].name);
    }
    resetHost();
  }

  private void resetHost() {
    name.setText("");
    port.setText("");
    ssl.setSelected(false);
    domains.setText("");
    docPath.setText("");
    currentIdx = -1;
  }

  private void loadHost(int idx) {
    saveHost(currentIdx);
    Host host = config.host[idx];
    enabled.setSelected(host.enabled);
    name.setText(host.name);
    port.setText("" + host.port);
    ssl.setSelected(host.ssl);
    domains.setText(host.domains);
    docPath.setText(host.docPath);
    cgi.setSelected(host.cgi);
    currentIdx = idx;
  }

  private void saveHost(int idx) {
    if (idx == -1) return;
    Host host = config.host[idx];
    host.name = name.getText();
    host.enabled = enabled.isSelected();
    host.port = JF.atoi(port.getText());
    host.ssl = ssl.isSelected();
    host.domains = domains.getText();
    host.docPath = docPath.getText();
    host.cgi = cgi.isSelected();
    if (host.docPath.endsWith("/")) {
      host.docPath = host.docPath.substring(0, host.docPath.length()-1);
    }
  }

  private void addHost(String name) {
    name = name.trim().replaceAll("\"", "");
    name = name.replaceAll(" ", "-");
    if (name.length() == 0) return;
    for(int a=0;a<config.host.length;a++) {
      if (config.host[a].name.equalsIgnoreCase(name)) {
        JFAWT.showError("Error", "That name already exists");
        return;
      }
    }
    //copy default values
    Host newhost = new Host();
    Host def = config.host[0];
    newhost.name = name;
    newhost.port = def.port;
    newhost.ssl = def.ssl;
    newhost.docPath = def.docPath;
    newhost.domains = def.domains;
    config.host = Arrays.copyOf(config.host, config.host.length + 1);
    config.host[config.host.length-1] = newhost;
    updateConfig();
  }

  private void delHost(int idx) {
    if (idx <= 1) {JFAWT.showError("Error", "Can not delete 'Default' host"); return;}
    Host host = config.host[idx];
    if (!JFAWT.showConfirm("Confirm", "Are you sure you want to delete '" + host.name + "'?")) return;
    int len = config.host.length;
    Host newList[] = new Host[len-1];
    System.arraycopy(config.host, 0, newList, 0, idx);
    System.arraycopy(config.host, idx+1, newList, idx, len - idx - 1);
    config.host = newList;
    updateConfig();
  }

  private void saveConfig() {
    //save config to configFile
    saveHost(currentIdx);
    try {
      XML xml = new XML();
      File tmpFile = File.createTempFile("apache", ".xml");
      FileOutputStream fos = new FileOutputStream(tmpFile);
      xml.readClass("apache", config);
      xml.write(fos);
      fos.close();
      Linux.mkdir(configFolder);
      if (!Linux.copyFile(tmpFile.getAbsolutePath(), configFolder + configFile)) {
        tmpFile.delete();
        throw new Exception("file io error");
      }
      tmpFile.delete();
    } catch (Exception e) {
      JFLog.log(e);
    }
  }

  private void applyHost(Host host, OutputStream os) throws Exception {
    byte data[] = null;
    if (!host.ssl) {
      data = JF.readAll(this.getClass().getClassLoader().getResourceAsStream("apache-default.conf"));
    } else {
      data = JF.readAll(this.getClass().getClassLoader().getResourceAsStream("apache-ssl.conf"));
    }
    String str = new String(data);
    str = str.replaceAll("[$]DOMAINS", host.domains);
    str = str.replaceAll("[$]PORT", "" + host.port);
    str = str.replaceAll("[$]EMAIL", "webmaster@localhost");
    str = str.replaceAll("[$]DOCPATH", host.docPath);
    str = str.replaceAll("[$]PUBLICKEY", "/etc/jconfig.d/apache/" + host.name + "/public.crt");
    str = str.replaceAll("[$]PRIVATEKEY", "/etc/jconfig.d/apache/" + host.name + "/private.key");
    if (host.cgi) {
      byte cgi[] = JF.readAll(this.getClass().getClassLoader().getResourceAsStream("apache-cgi.conf"));
      str = str.replaceAll("[$]CGI", new String(cgi));
    } else {
      str = str.replaceAll("[$]CGI", "");
    }
    os.write(str.getBytes());
  }

  private void apply() {
    //save each vhost to /etc/apache2/sites-available
    try {
      for(int a=0;a<config.host.length;a++) {
        Host host = config.host[a];
        File tmpFile = File.createTempFile("apache", ".conf");
        FileOutputStream fos = new FileOutputStream(tmpFile);
        applyHost(host, fos);
        fos.close();
        if (!Linux.copyFile(tmpFile.getAbsolutePath(), "/etc/apache2/sites-available/" + host.name)) {
          tmpFile.delete();
          throw new Exception("file io error");
        }
        tmpFile.delete();
        if (host.enabled) {
          Linux.createLink("/etc/apache2/sites-available/" + host.name, "/etc/apache2/sites-enabled/" + host.name);
        } else {
          Linux.deleteFile("/etc/apache2/sites-enabled/" + host.name);
        }
      }
      JFAWT.showMessage("Notice", "Please restart server to make changes effective.");
    } catch (Exception e) {
      JFLog.log(e);
    }
  }

  private void restart() {
    if (Linux.restartService("apache2"))
      JFAWT.showMessage("Notice", "Apache Service Restarted");
    else
      JFAWT.showError("Error", "Failed to Restart Apache Service");
  }
}
